package net.ocara.cpfj.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class CPFJ implements EntryPoint {
	
	private static final String naoDigite = "não digite: / . -";
	
	private static final String SERVER_ERROR = "Ocorreu um erro durante "
		+ "acesso ao servidor. Por favor verifique sua conexão na rede "
		+ "e tente novamente.";
	
	private final ValidatingServiceAsync validatingService = GWT
	.create(ValidatingService.class);

	  public void onModuleLoad() {
			final Button validarButton = new Button("Validar");
			final Button limparButton = new Button("Limpar");
			final Button gerarCPFButton = new Button("Gerar CPF");
			final Button gerarCNPJButton = new Button("Gerar CNPJ");
			final Button ajudarButton = new Button("Ajuda?");
			final TextBox cpfjText = new TextBox();
			cpfjText.setText(naoDigite);

			// We can add style names to widgets
			validarButton.addStyleName("sendButton");

			// Add the nameField and sendButton to the RootPanel
			// Use RootPanel.get() to get the entire body element
			RootPanel.get("cpfjFieldContainer").add(cpfjText);
			RootPanel.get("validButtonContainer").add(validarButton);
			RootPanel.get("cleanButtonContainer").add(limparButton);
			RootPanel.get("cpfButtonContainer").add(gerarCPFButton);
			RootPanel.get("cnpjButtonContainer").add(gerarCNPJButton);
			RootPanel.get("helpButtonContainer").add(ajudarButton);

			// Focus the cursor on the name field when the app loads
			cpfjText.setFocus(true);
			cpfjText.selectAll();

			// Create the popup dialog box
			final DialogBox resultDialogBox = new DialogBox();
			resultDialogBox.setText("Resultado da validação");
			resultDialogBox.setAnimationEnabled(true);
			final Button closeButton = new Button("Voltar");
			// We can set the id of a widget by accessing its Element
			closeButton.getElement().setId("closeButton");
			final Label textToServerLabel = new Label();
			final HTML serverResponseLabel = new HTML();
			VerticalPanel dialogVPanel = new VerticalPanel();
			dialogVPanel.addStyleName("dialogVPanel");
			dialogVPanel.add(serverResponseLabel);
			dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
			dialogVPanel.add(closeButton);
			resultDialogBox.setWidget(dialogVPanel);

			// Add a handler to close the DialogBox
			closeButton.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					resultDialogBox.hide();
					validarButton.setEnabled(true);
					validarButton.setFocus(true);
				}
			});

			// Create a handler for the sendButton and nameField
			class MyHandler implements ClickHandler, KeyUpHandler {
				/**
				 * Fired when the user clicks on the sendButton.
				 */
				public void onClick(ClickEvent event) {
					if (event.getSource().equals(cpfjText)) {
						if (cpfjText.getText().equals(naoDigite)) {
							cpfjText.setText("");
						}
					} else if (event.getSource().equals(validarButton)) {
						if (!cpfjText.getText().equals(naoDigite)) {
							validarCpfCnpj();
						}
					} else if (event.getSource().equals(limparButton)) {
						cpfjText.setText(naoDigite);
					} else if (event.getSource().equals(gerarCPFButton)) {
						gerarCPF();
					} else if (event.getSource().equals(gerarCNPJButton)) {
						gerarCNPJ();
					} else if (event.getSource().equals(ajudarButton)) {
						ajuda();
					}					
				}

				/**
				 * Fired when the user types in the nameField.
				 */
				public void onKeyUp(KeyUpEvent event) {
					if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
						validarCpfCnpj();
					}
				}

				/**
				 * Send the name from the nameField to the server and wait for a response.
				 */
				private void validarCpfCnpj() {
					validarButton.setEnabled(false);
					String textToServer = cpfjText.getText().trim();
					textToServerLabel.setText(textToServer);
					serverResponseLabel.setText("");
					validatingService.validateCPFJ(textToServer,
							new AsyncCallback<String>() {
								public void onFailure(Throwable caught) {
									// Show the RPC error message to the user
									resultDialogBox
											.setText("CPFJ: erro ao validar CPF ou CNPJ!");
									serverResponseLabel
											.addStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(SERVER_ERROR);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}

								public void onSuccess(String result) {
									resultDialogBox.setText("CPFJ: CPF ou CNPJ validado com sucesso!");
									serverResponseLabel
											.removeStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(result);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}
							});
				}
				
				private void gerarCPF() {
					validarButton.setEnabled(false);
					serverResponseLabel.setText("");
					validatingService.genCPF(
							new AsyncCallback<String>() {
								public void onFailure(Throwable caught) {
									// Show the RPC error message to the user
									resultDialogBox
											.setText("CPFJ: erro ao gerar CPF aleatório!");
									serverResponseLabel
											.addStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(SERVER_ERROR);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}

								public void onSuccess(String result) {
									resultDialogBox.setText("CPFJ: CPF aleatório gerado com sucesso!");
									serverResponseLabel
											.removeStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(result);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}
							});
				}
				
				private void gerarCNPJ() {
					validarButton.setEnabled(false);
					serverResponseLabel.setText("");
					validatingService.genCNPJ(
							new AsyncCallback<String>() {
								public void onFailure(Throwable caught) {
									// Show the RPC error message to the user
									resultDialogBox
											.setText("CPFJ: erro ao gerar CNPJ aleatório!");
									serverResponseLabel
											.addStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(SERVER_ERROR);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}

								public void onSuccess(String result) {
									resultDialogBox.setText("CPFJ: CNPJ aleatório gerado com sucesso!");
									serverResponseLabel
											.removeStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(result);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}
							});
				}
				
				private void ajuda() {
					validarButton.setEnabled(false);
					serverResponseLabel.setText("");
					validatingService.sysInfoHelp(
							new AsyncCallback<String>() {
								public void onFailure(Throwable caught) {
									// Show the RPC error message to the user
									resultDialogBox
											.setText("CPFJ: erro ao solicitar ajuda!");
									serverResponseLabel
											.addStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(SERVER_ERROR);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}

								public void onSuccess(String result) {
									resultDialogBox.setText("CPFJ: ajuda?");
									serverResponseLabel
											.removeStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(result);
									resultDialogBox.center();
									closeButton.setFocus(true);
								}
							});
				}
			}

			// Add a handler to send the name to the server
			MyHandler handler = new MyHandler();
			validarButton.addClickHandler(handler);
			limparButton.addClickHandler(handler);
			gerarCPFButton.addClickHandler(handler);
			gerarCNPJButton.addClickHandler(handler);
			ajudarButton.addClickHandler(handler);
			
			cpfjText.addClickHandler(handler);
			cpfjText.addKeyUpHandler(handler);
		}
}
